package com.sihai.ehr.web.action.salary;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.SalaryStatistics;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.SalaryStatisticsService;
import com.sihai.ehr.utils.SalaryStatisticsUtil;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.action.ExportAction;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Wang.Yi
 * Date: 2013-3-2
 * Time: 11:00:50
 * To change this template use File | Settings | File Templates.
 */
@Results({
        @Result(name = "main", location = "/WEB-INF/pages/salary/salary_main.jsp"),
        @Result(name = "list", location = "salary_statistics.jsp"),
        @Result(name = "salary_person_statistics", location = "/WEB-INF/pages/salary/salary_person_statistics.jsp"),
        @Result(name = "staff_salary_statistics", location = "/WEB-INF/pages/salary/staff_salary_statistics.jsp")
})
public class SalaryStatisticsAction extends ExportAction {

    @BeanInject
    private OrganizationService organizationService;
    @BeanInject
    private SalaryStatisticsService salaryStatisticsService;
    private List<Organization> organizations;

    private LimitedList<SalaryStatistics> salaryStatisticses;

    private boolean showYearMonth;
    private int startYear;
    private int endYear;
    private int year;
    private int month;

    private String result;

    private Map<String,Float> totalMap;
    
    @Action("/salary/salary_statistics_main")
    public String execute() throws Exception {
        listAction = "/salary/salary_statistics_list.xhtml";
        listTitle = "薪资福利管理统计";

        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        showChildOrg = true;
        showYearMonth = true;
        try{
            startYear = NumberUtils.createInteger(PropertiesLoaderUtils.loadAllProperties("jdbc.properties").getProperty("attendance_start_year", "2001"));
        }catch (Exception e){
            startYear = 2001;
        }
        setCurrentYearAndMonth();
        return "main";
    }

    private void setCurrentYearAndMonth(){
        endYear = Calendar.getInstance().get(Calendar.YEAR);
        year = endYear;
        month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        /*if(month == 0){
            month = 12;
            year = year-1;
        }*/
    }
    @Action("/salary/salary_statistics_list")
    public String list() throws Exception {
        Long orgId = NumberUtils.createLong(getParameter("selectionOrgId"));
        Long dutyId = NumberUtils.createLong(getParameter("selectionDutyId"));
        Long searchOrgId = (orgId == null || orgId <= 0 ? organizationId : orgId);
        if(year <= 0 || month <= 0){
            setCurrentYearAndMonth();
        }
        salaryStatisticses=salaryStatisticsService.find(year,month,searchOrgId,dutyId,createSorter().asc("st.employeeinfoWork.workNo"),createLimit());
        totalMap= SalaryStatisticsUtil.getTotalAmount(salaryStatisticses);  //计算方案总金额
        //分页
        this.setPageUrl("salary/salary_statistics_list.xhtml");
        this.paging(salaryStatisticses);
        return "list";
    }

    //导出
    @Action(value = "/salary/statistics-report", results = {
            @Result(name = EXPORT_SUCCESS, type = "stream",
                    params = {"contentType", "application/vnd.ms-excel", "contentDisposition", "attachment;fileName=\"${fileName}.xls\""})
    })
    public String report() throws Exception{
        Long orgId = NumberUtils.createLong(getParameter("selectionOrgId"));
        Long dutyId = NumberUtils.createLong(getParameter("selectionDutyId"));
        Long searchOrgId = (orgId == null || orgId <= 0 ? organizationId : orgId);
        if(year <= 0 || month <= 0){
            setCurrentYearAndMonth();
        }
        return export(salaryStatisticsService.find(year,month,searchOrgId,dutyId,null, null));
    }

    //将数据库中行变成excel列的方式导出
    @Action(value = "/ajax/statistics-report", results = {@Result(name = "success", type = "json", params = {"root", "result"})})
    public String reportByDetail(){
        Long orgId = NumberUtils.createLong(getParameter("selectionOrgId"));
        Long dutyId = NumberUtils.createLong(getParameter("selectionDutyId"));
        Long searchOrgId = (orgId == null || orgId <= 0 ? organizationId : orgId);
        if(year <= 0 || month <= 0){
            setCurrentYearAndMonth();
        }
        List<SalaryStatistics> statisticses = salaryStatisticsService.find(year,month,searchOrgId,dutyId,null, null);
        String saveFile = String.format("D://ehr_salary_report_%s_%s.xls", year, month);
        try{
            Boolean b = salaryStatisticsService.report(statisticses, saveFile);
            if(b){
                result = "success:"+saveFile;
            }else{
                result = "error:data_empty";
            }
        }catch (Exception e){
            result = "error:"+e.getMessage();
        }

        return SUCCESS;
    }

    //-----------------------个人--------------------
    /*@Action("/public/salary_person_statistics_main")
    public String dispatchPersonStatis() throws Exception {
        listAction = "/public/salary_person_statistics.xhtml";
        listTitle = "薪资福利管理统计";

        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        showChildOrg = true;
        showYearMonth = true;
        try{
            startYear = NumberUtils.createInteger(PropertiesLoaderUtils.loadAllProperties("jdbc.properties").getProperty("attendance_start_year", "2001"));
        }catch (Exception e){
            startYear = 2001;
        }
        setCurrentYearAndMonth();
        return "main";
    }*/

    @Action("/public/salary_person_statistics")
    public String personList() throws Exception {
        try{
            startYear = NumberUtils.createInteger(PropertiesLoaderUtils.loadAllProperties("jdbc.properties").getProperty("attendance_start_year", "2001"));
        }catch (Exception e){
            startYear = 2001;
        }
        endYear = Calendar.getInstance().get(Calendar.YEAR);
        if(year <= 0 || month <= 0){
            setCurrentYearAndMonth();
        }
        User user = getCurrentUser();
        if(user != null && user.getId() != null && user.getId() > 0){
            salaryStatisticses=salaryStatisticsService.findByUserId(year,month,user.getWork().getId(),createSorter(),createLimit());
            totalMap= SalaryStatisticsUtil.getTotalAmount(salaryStatisticses);  //计算方案总金额
        }
        return "salary_person_statistics";
    }
    
    @Action("/public/staff_salary_statistics")
    public String personSalaryList() throws Exception {
        User user = getCurrentUser();
        if(user != null && user.getId() != null && user.getId() > 0){
            salaryStatisticses=salaryStatisticsService.findByUserId(year,month,user.getWork().getId(),createSorter(),createLimit());
            totalMap= SalaryStatisticsUtil.getTotalAmount(salaryStatisticses);  //计算方案总金额
        }
        return "staff_salary_statistics";
    }
    
    @Override
    protected String getTemplate() {
        return "salary_statistics_report.xls";
    }

    @Override
    protected String fileName() {
        return "salary_statistics_report_"+System.currentTimeMillis();
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public void setOrganizations(List<Organization> organizations) {
        this.organizations = organizations;
    }

    public LimitedList<SalaryStatistics> getSalaryStatisticses() {
        return salaryStatisticses;
    }

    public void setSalaryStatisticses(LimitedList<SalaryStatistics> salaryStatisticses) {
        this.salaryStatisticses = salaryStatisticses;
    }

    public boolean isShowYearMonth() {
        return showYearMonth;
    }

    public void setShowYearMonth(boolean showYearMonth) {
        this.showYearMonth = showYearMonth;
    }

    public int getStartYear() {
        return startYear;
    }

    public void setStartYear(int startYear) {
        this.startYear = startYear;
    }

    public int getEndYear() {
        return endYear;
    }

    public void setEndYear(int endYear) {
        this.endYear = endYear;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public Map<String, Float> getTotalMap() {
        return totalMap;
    }

    public void setTotalMap(Map<String, Float> totalMap) {
        this.totalMap = totalMap;
    }

    public String getResult() {
        return result;
    }
}
